/**
 * Created with IntelliJ IDEA.
 *
 * @author: cxs
 * @date: 2023/6/26
 * @time: 20:49
 * @className：UserServiceImpl
 * @description：
 */
package com.bailan.sys.service.impl;

import com.bailan.common.util.DataGridView;
import com.bailan.common.util.SysConstant;
import com.bailan.sys.domain.User;
import com.bailan.sys.mapper.RoleMapper;
import com.bailan.sys.mapper.UserMapper;
import com.bailan.sys.service.IUserService;
import com.bailan.sys.vo.UserVo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;

@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    /**
     * 用户登录的核心方法
     * @param userVo
     * @return
     */
    @Override
    public User login(UserVo userVo) {
        //根据账号和密码查询
        //先对userVo的密码加密
        String pwd= DigestUtils.md5DigestAsHex(userVo.getPwd().getBytes());
        userVo.setPwd(pwd);
        //调用userMapper接口的查询方法
        return userMapper.isUserExist(userVo);
    }
    /**
     * 查询所有用户
     *
     * @param userVo
     * @return
     */
    @Override
    public DataGridView queryAllUser(UserVo userVo) {
        Page<Object> page= PageHelper.startPage(userVo.getPage(), userVo.getLimit());

        List<User> data=this.userMapper.queryAllUser();
        return  new DataGridView(page.getTotal(),data);
    }

    /**
     * 添加用户
     *
     * @param userVo
     */
    @Override
    public void addUser(UserVo userVo) {
        //设置默认密码
        userVo.setPwd(DigestUtils.md5DigestAsHex(SysConstant.USER_DEFAULT_PASSWORD.getBytes()));
        userVo.setType(SysConstant.USER_TYPE_NORMAL);
        this.userMapper.insertSelective(userVo);
    }

    /**
     * 修改用户
     * @param userVo
     */
    @Override
    public void updateUser(UserVo userVo) {
        this.userMapper.updateByPrimaryKeySelective(userVo);
    }

    /**
     * 删除用户
     * @param userid
     */
    @Override
    public void deleteUser(Integer userid) {
        //先删除用户
        this.userMapper.deleteByPrimaryKey(userid);
        //根据用户id删除sys_role_user
        this.roleMapper.deleteRoleUserByUid(userid);
    }

    /**
     * 批量删除
     *
     * @param ids
     */
    @Override
    public void deleteBatchUser(Integer[] ids) {
        for (Integer id:ids) {
            deleteUser(id);
        }
    }

    /**
     * 重置密码
     *
     * @param userid
     */
    @Override
    public void resetUserPwd(Integer userid) {
        User user = new User();
        user.setUserid(userid);
        //设置默认密码
        user.setPwd(DigestUtils.md5DigestAsHex(SysConstant.USER_DEFAULT_PASSWORD.getBytes()));
        //设置完成后更新
        this.userMapper.updateByPrimaryKeySelective(user);
    }


}
